package com.cqie.secondhandtransaction.service.Impl.login;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cqie.secondhandtransaction.DTO.UserDetailsDTO;
import com.cqie.secondhandtransaction.entity.UserInfo;
import com.cqie.secondhandtransaction.mapper.UserInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 加载用户信息，不进行认证功能和权限校验
     * @param username
     * @return
     */
    @Override
    public UserDetailsDTO loadUserByUsername(String username) {
        UserInfo user = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getUserName, username));
        if (user == null) {
            throw new UsernameNotFoundException("User not found");
        }

        UserDetailsDTO dto = new UserDetailsDTO();
        BeanUtils.copyProperties(user, dto);
        return new UserDetailsDTO(
                user.getUserName(),
                user.getPassword(),
                getAuthorities(user.getRole()),
                user
        );
    }

    private List<GrantedAuthority> getAuthorities(Integer role) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        if (role == 0) {
            //管理员
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        } else if (role == 1) {
            //用户
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        }
        return authorities;
    }
}

